import { observable } from 'mobx';
import { MenuConfigItem } from '~/config/menus';

export interface MenuItem {
  id: string
  icon?: JSX.Element
  name: string
  path: string
  hide?: boolean
  parentItem?: SubMenuItem
}

export interface SubMenuItem {
  id: string
  icon?: JSX.Element
  name: string
  path: string
  hide?: boolean
  expand: boolean
  subMenu: Array<MenuItem | SubMenuItem>
  parentItem?: SubMenuItem
}

export const menuMap = new Map<string, MenuItem>();

let currentId = 0;

const getId = () => {
  currentId += 1;

  return currentId.toString();
};

const resolveMenuDataItem = (menuDataItem: MenuConfigItem): MenuItem | SubMenuItem => {
  if (!menuDataItem.children) {
    const item: MenuItem = {
      id: getId(),
      icon: menuDataItem.icon,
      name: menuDataItem.name,
      path: menuDataItem.path,
      hide: menuDataItem.hide,
    };

    menuMap.set(menuDataItem.path, item);

    return item;
  }

  const item: SubMenuItem = {
    id: getId(),
    icon: menuDataItem.icon,
    name: menuDataItem.name,
    path: menuDataItem.path,
    hide: menuDataItem.hide,
    expand: false,
    subMenu: [],
  };

  item.subMenu = menuDataItem.children.map((v) => {
    const subItem = resolveMenuDataItem(v);
    subItem.parentItem = item;
    return subItem;
  });

  menuMap.set(menuDataItem.path, item);

  return item;
};

// local menu data
// export const MenuList = observable.array(menuData.map((v) => resolveMenuDataItem(v)), { deep: false });

// remote menu data formater
export const formatMenuList = (menu: any = []): Array<any> => observable.array(menu.map((v: any) => resolveMenuDataItem(v)), { deep: false });
